package com.CmJava.crowd.service.imp;


import com.CmJava.crowd.entity.ResultEntity;
import com.CmJava.crowd.entity.*;
import com.CmJava.crowd.mapper.GoodMapper;
import com.CmJava.crowd.mapper.UserAndGoodMapper;
import com.CmJava.crowd.mapper.UserMapper;
import com.CmJava.crowd.service.GoodsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class GoodsServiceImp implements GoodsService {

    @Autowired
    private GoodMapper goodMapper;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private UserAndGoodMapper userAndGoodMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public PageInfo<Good> goodsList(int cp, int pageNum, String keyWord) {
        // 开启分页功能
        PageHelper.startPage(cp,pageNum);
        List<Good> goods = goodMapper.goodList(keyWord);
        // 封装到PageInfo中
        PageInfo<Good> goodPageInfo = new PageInfo<>(goods);
        return goodPageInfo;
    }

    @Override
    public ResultEntity getOneGood(String primaryKey) {
        Good good = goodMapper.selectByPrimaryKey(Integer.parseInt(primaryKey));
        return ResultEntity.successWithData(good);
    }

    @Override
    public ResultEntity getGoodChart(String primaryKey) {
        String key = primaryKey + "-14Days";
        FundMoneyBy14Days fundMoneyBy14Days = new FundMoneyBy14Days(Integer.parseInt(primaryKey),null);
        // 检查redis里面有没有这个商品的14天众筹信息
        if(redisTemplate.hasKey(key)){
            fundMoneyBy14Days = (FundMoneyBy14Days) redisTemplate.opsForValue().get(key);
            ArrayList<FundMoneyBy14Days.DateAndMoney> fundMoney = fundMoneyBy14Days.getFundMoney();
            int size = fundMoney.size();
            fundMoneyBy14Days.setFundPeople(size);

            addZeroIfNotToday(fundMoney,size,fundMoneyBy14Days);
            fundMoneyBy14Days.setFundPeople(size);
        }else{
            // 没有人捐过钱
            HashMap<String, Integer> hashMap = new HashMap<>();
            hashMap.put(new SimpleDateFormat("yyyy-MM-dd").format(new Date()),0);
            FundMoneyBy14Days.DateAndMoney dateAndMoney = fundMoneyBy14Days.new DateAndMoney(hashMap);
            ArrayList<FundMoneyBy14Days.DateAndMoney> dateAndMonies = new ArrayList<>();
            dateAndMonies.add(dateAndMoney);
            fundMoneyBy14Days.setFundMoney(dateAndMonies);
            redisTemplate.opsForValue().set(key,fundMoneyBy14Days);

            System.out.println(fundMoneyBy14Days.getFundMoney());

            ArrayList<FundMoneyBy14Days.DateAndMoney> fundMoney = fundMoneyBy14Days.getFundMoney();
            int size = fundMoney.size();
            fundMoneyBy14Days.setFundPeople(size);
            addZeroIfNotToday(fundMoney,size,fundMoneyBy14Days);
            fundMoneyBy14Days.setFundPeople(size);
        }
        System.out.println(fundMoneyBy14Days.getFundMoney());
        return ResultEntity.successWithData(fundMoneyBy14Days);
    }

    @Override
    public ResultEntity updateGoodChart(String primaryKey, String fundDate, String fundMoney) {
        String key = primaryKey + "-14Days";
        if(redisTemplate.hasKey(key)){
            FundMoneyBy14Days fundMoneyBy14Days= (FundMoneyBy14Days) redisTemplate.opsForValue().get(key);
            fundMoneyBy14Days=updateRedis14Days(fundMoneyBy14Days,fundDate,fundMoney,primaryKey);
            redisTemplate.opsForValue().set(key,fundMoneyBy14Days);
            // 把mysql的数据也更新一下
            Good good = goodMapper.selectByPrimaryKey(Integer.parseInt(primaryKey));
            Integer currentAmount = good.getCurrentamount();
            Integer targetAmount = good.getTargetamount();
            if ((currentAmount+Integer.parseInt(fundMoney))>=targetAmount){
                good.setIspass(1);
            }
            good.setCurrentamount(currentAmount+Integer.parseInt(fundMoney));
            goodMapper.updateByPrimaryKey(good);
            return ResultEntity.successWithoutData();
        }else {
            return ResultEntity.failWithoutMessage();
        }
    }

    @Override
    public ResultEntity indexGoodInf() {
        List<Good> goods = goodMapper.allGood();
        int totalGoodNum = goods.size();
        int sum=0;
        int isPassNum=0;
        int notPassNum=0;
        for (Good good : goods) {
            sum+=good.getCurrentamount();
            if (good.getIspass()==0){
                notPassNum++;
            }else {
                isPassNum++;
            }
        }
        double passRate=Math.floor(isPassNum/totalGoodNum*100)/100;
        return ResultEntity.successWithData(totalGoodNum+"-"+sum+"-"+passRate);
    }

    @Override
    public ResultEntity indexTodayInf() {
        String key="todayFundInf";
        TodayFundInfo todayFundInfo = (TodayFundInfo) redisTemplate.opsForValue().get(key);
        if (todayFundInfo!=null){
            return ResultEntity.successWithData(todayFundInfo);
        }
        return ResultEntity.failWithoutMessage();
    }


    private FundMoneyBy14Days updateRedis14Days(FundMoneyBy14Days fundMoneyBy14Days, String fundDate, String fundMoney,String primaryKey) {

        ArrayList<FundMoneyBy14Days.DateAndMoney> fundMoney1 = fundMoneyBy14Days.getFundMoney();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        FundMoneyBy14Days fundMoneyBy14Days1=new FundMoneyBy14Days();
        int i=100;
        int money=0;
        FundMoneyBy14Days.DateAndMoney dateAndMoney0;
        for (int j = fundMoney1.size()-1; j >= 0; j--) {
            FundMoneyBy14Days.DateAndMoney dateAndMoney=fundMoney1.get(j);
            Set<String> keySet = dateAndMoney.keySet();
            for (String key : keySet) {
                Date parseOld=null;
                Date parseNew=null;
                try {
                parseOld = simpleDateFormat.parse(key);
                parseNew = simpleDateFormat.parse(fundDate);
                }catch (Exception e){
                    e.printStackTrace();
                }
                // 1：parseOld更大    -1：parseOld更小     0：就是parseOld那天
                i = parseOld.compareTo(parseNew);
                if (i==0){
                    money = dateAndMoney.get(key);
                }
            }
            if (i==1){
                //parseOld更大
                if (fundMoney1.size()==1){
                    HashMap<String, Integer> hashMap = new HashMap<>();
                    hashMap.put(fundDate,Integer.parseInt(fundMoney));
                    dateAndMoney0= fundMoneyBy14Days1.new DateAndMoney(hashMap);
                    fundMoney1.add(0,dateAndMoney0);
                    break;
                }else {
                    continue;
                }
            }else if (i==-1){
                int index = fundMoney1.indexOf(dateAndMoney);
                HashMap<String, Integer> hashMap = new HashMap<>();
                hashMap.put(fundDate,Integer.parseInt(fundMoney));
                dateAndMoney0= fundMoneyBy14Days1.new DateAndMoney(hashMap);
                fundMoney1.add(index+1,dateAndMoney0);
                break;
            }else if (i==0){
                // 这个日期已经有数据了
                int index = fundMoney1.indexOf(dateAndMoney);
                HashMap<String, Integer> hashMap = new HashMap<>();
                hashMap.put(fundDate,Integer.parseInt(fundMoney)+money);
                dateAndMoney0= fundMoneyBy14Days1.new DateAndMoney(hashMap);
                fundMoney1.set(index,dateAndMoney0);
                break;
            }
        }
        fundMoneyBy14Days.setFundMoney(fundMoney1);


        // 更新今日捐款的信息
        todayFund(primaryKey,fundMoney,fundDate);

        return fundMoneyBy14Days;
    }

    private void addZeroIfNotToday(ArrayList<FundMoneyBy14Days.DateAndMoney> fundMoney ,
                                   int size, FundMoneyBy14Days fundMoneyBy14Days){
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String theDay ="";
        String[] Day14=new String[14];
        for (int i = 12; i >= 0; i--) {
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            theDay = simpleDateFormat.format(calendar.getTime());
            Day14[i]=theDay;
        }
        Day14[13]=simpleDateFormat.format(date);

        int count=0;
        ArrayList<FundMoneyBy14Days.DateAndMoney> list = new ArrayList<>();
        FundMoneyBy14Days fundMoneyBy14Days1=new FundMoneyBy14Days();
        Integer money=0;
        for (String theday : Day14) {
            for (FundMoneyBy14Days.DateAndMoney dateAndMoney : fundMoney) {
                Set<String> keySet = dateAndMoney.keySet();
                for (String key : keySet) {
                    if (key.equals(theday)){
                        count=1;
                        money = dateAndMoney.get(key);
                    }
                }
                if (count==1){break;}
            }
            HashMap<String, Integer> hashMap = new HashMap<>();
            FundMoneyBy14Days.DateAndMoney dateAndMoney;
            if (count==1){
                hashMap.put(theday,money);

            }else{
                hashMap.put(theday,0);
            }
            dateAndMoney= fundMoneyBy14Days1.new DateAndMoney(hashMap);
            list.add(dateAndMoney);
            count=0;
        }
        fundMoneyBy14Days.setFundMoney(list);
    }

    private void todayFund(String primaryKey, String fundMoney,String fundDate) {
        String key="todayFundInf";
        String todayTime0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        String todayDate = todayTime0.split(" ")[0];
        String todayTime = todayTime0.split(" ")[1];
        if (!fundDate.equals(todayDate)) {
            //捐款页面如果不是今天捐款，则不会存数据到redis
            return;
        }
        // 被捐款的商品
        Good good = goodMapper.selectByPrimaryKey(Integer.parseInt(primaryKey));

        // 该商品的所有者
        UserAndGoodExample userAndGoodExample = new UserAndGoodExample();
        UserAndGoodExample.Criteria criteria = userAndGoodExample.createCriteria();
        criteria.andGoodidEqualTo(good.getId());
        List<UserAndGood> userAndGoods = userAndGoodMapper.selectByExample(userAndGoodExample);
        if (userAndGoods.size()!=1){
            throw new RuntimeException();
        }
        UserAndGood userAndGood = userAndGoods.get(0);
        User user = userMapper.selectByPrimaryKey(userAndGood.getUserid());

        TodayFundInfo todayFundInfo=null;
        if(redisTemplate.hasKey(key)){
            todayFundInfo = (TodayFundInfo) redisTemplate.opsForValue().get(key);
            if(!todayFundInfo.getTodayDate().equals(todayDate)){
                // 捐款过的日期不是今天，要清空
                List<TodayFundGood> goodList = new ArrayList<>();
                goodList.add(new TodayFundGood(good.getId(),user.getId(),good.getGoodname(),
                        user.getUsername(),good.getCurrentamount()+Integer.parseInt(fundMoney),
                        good.getTargetamount(),Integer.parseInt(fundMoney),todayTime));

                todayFundInfo = new TodayFundInfo(1, Integer.parseInt(fundMoney), todayDate, goodList);

            }else {
                //  捐款过的日期是今天，要覆盖
                todayFundInfo.setGetFundNum(todayFundInfo.getGetFundNum()+1);
                todayFundInfo.setGetTotalMoney(todayFundInfo.getGetTotalMoney()+Integer.parseInt(fundMoney));

                int sum=0;
                List<TodayFundGood> goodList = todayFundInfo.getGoodList();
                for (int i = goodList.size()-1; i >=0 ; i--) {
                    if (goodList.get(i).getGoodId()==good.getId()){
                        sum=goodList.get(i).getTodayGetMoney();
                        break;
                    }
                }
//                int count=0;
//                for (TodayFundGood todayFundGood : goodList) {
//                    if (todayFundGood.getGoodId()==good.getId()){
//                        // 当天的该商品已经有过捐款
//                        todayFundGood.setCurrentAmount(todayFundGood.getCurrentAmount()+Integer.parseInt(fundMoney));
//                        todayFundGood.setTodayGetMoney(todayFundGood.getTodayGetMoney()+Integer.parseInt(fundMoney));
//                        count++;
//                        break;
//                    }
//                }
                // 当天的该商品第一次得到捐款
//                if (count==0) {
                    goodList.add(new TodayFundGood(good.getId(), user.getId(), good.getGoodname(),
                            user.getUsername(), good.getCurrentamount() + Integer.parseInt(fundMoney),
                            good.getTargetamount(), Integer.parseInt(fundMoney)+sum,todayTime));
//                }
            }
        }else {
            // 第一次，没有任何key
            List<TodayFundGood> goodList = new ArrayList<>();
            goodList.add(new TodayFundGood(good.getId(), user.getId(), good.getGoodname(),
                    user.getUsername(), good.getCurrentamount() + Integer.parseInt(fundMoney),
                    good.getTargetamount(), Integer.parseInt(fundMoney),todayTime));
            todayFundInfo = new TodayFundInfo(1, Integer.parseInt(fundMoney), todayDate, goodList);
        }
        System.out.println(todayFundInfo);
        redisTemplate.opsForValue().set(key,todayFundInfo);
    }
}


